package com.qx.cn.tool;

import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import com.qx.cn.model.User;
import com.qx.cn.service.MenuService;

/**
 * 
 * 用户登录检查拦截器
 * 
 * @author 00fly
 * @version [版本号, 2016-4-20]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
public class LoginInterceptor extends AbstractInterceptor
{
    /**
     * 注释内容
     */
    private static final long serialVersionUID = 4666945322331493553L;
    
    @Autowired
    private MenuService menuService;
    
    private List menuURLs = null; // 需要做URL权限校验的菜单
    
    @Override
    public void init()
    {
        super.init();
        if (menuURLs == null)
        {
            menuURLs = menuService.queryAllMenuURL();
        }
    }
    
    @Override
    public String intercept(ActionInvocation invocation)
        throws Exception
    {
        HttpServletRequest request = ServletActionContext.getRequest();
        String path = StringUtils.substringAfter(request.getRequestURI(), request.getContextPath() + "/");
        User user = (User)ServletActionContext.getRequest().getSession().getAttribute("user");
        if (user != null)
        {
            // 取当前用户已分配菜单URL
            Set<String> menuSet = (Set<String>)ServletActionContext.getRequest().getSession().getAttribute("menuset");
            if (menuURLs.contains(path) && !menuSet.contains(path))
            {
                ServletActionContext.getRequest().getSession().removeAttribute("user");
                return "outlogin";
            }
            HttpSession session = ServletActionContext.getRequest().getSession();
            boolean flagOnLine = SessionListener.isOnline(session);
            if (flagOnLine)
            {
                return invocation.invoke();
            }
            ServletActionContext.getRequest().getSession().removeAttribute("user");
            return "outlogin";
        }
        return "outlogin";
    }
}